﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using Model;
using System.Text;

public partial class CustomersGo : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    { 
        if (!X.IsAjaxRequest)
        {  
            using (var m = new ACEntities())
            {
                var StoreBigClass = from c in m.Catalogs
                                    where c.ParentID == 0
                                    select c;
                List<Model.Catalogs> catalogses = new List<Model.Catalogs>();
                List<string> abcStrs = new List<string>(26);
                for (char a='A' ; a<='Z'; a++)
                {
                    abcStrs.Add(a.ToString());
                }
                int i = 0;
                foreach (var catalogse in StoreBigClass)
                {
                    var clg = catalogse;
                    
                    clg.ClassID = catalogse.ClassID;
                    clg.ClassName = abcStrs[i] + "--" + clg.ClassName;

                    catalogses.Add(clg);
                    i++;
                }
                StoreBC.DataSource = catalogses;
                StoreBC.DataBind();
                store3BigID.DataSource = catalogses;
                store3BigID.DataBind();
                if (Request["bid"] != null)
                {
                    X.AddScript("#{StoreSC}.reload();");
                    ComboBox2.SetValue(Request["bid"]);
                }
                StatusID.SelectedItem.Index = 0;
                StoreBC1.DataSource = catalogses;
                StoreBC1.DataBind(); 
            }
            return;

        }
    }

    protected void StoreSC_onRefresh(object sender, StoreReadDataEventArgs e)
    {
        int pid = int.Parse(ComboBox1.SelectedItem.Value);
        using (var m = new ACEntities())
        {
            var StoreSmallClass = from c in m.Catalogs
                                  where c.ParentID == pid
                                  select c;
            int i = 1;
            List<Model.Catalogs> catalogses = new List<Model.Catalogs>();
            foreach (var catalogse in StoreSmallClass)
            {
                var clg = catalogse;

                clg.ClassID = catalogse.ClassID;
                clg.ClassName = "["+i + "]--" + clg.ClassName;

                catalogses.Add(clg);
                i++;
            }
            StoreSC.DataSource = catalogses;
            StoreSC.DataBind();
        }
    }

    protected void StoreSC1_onRefresh(object sender, StoreReadDataEventArgs e)
    {
        int pid = int.Parse(BigClassID.SelectedItem.Value);
        
        using (var m = new ACEntities())
        {
            var StoreSmallClass = from c in m.Catalogs
                                  where c.ParentID == pid
                                  select c;
            int i = 1;
            List<Model.Catalogs> catalogses = new List<Model.Catalogs>();
            foreach (var catalogse in StoreSmallClass)
            {
                var clg = catalogse;

                clg.ClassID = catalogse.ClassID;
                clg.ClassName = "[" + i + "]--" + clg.ClassName;

                catalogses.Add(clg);
                i++;
            }
            StoreSC1.DataSource = catalogses;
            StoreSC1.DataBind();
        }
    }

    protected void store3SmallID_onRefresh(object sender, StoreReadDataEventArgs e)
    {
        int pid = int.Parse(tf3BigID.SelectedItem.Value);

        using (var m = new ACEntities())
        {
            var StoreSmallClass = from c in m.Catalogs
                                  where c.ParentID == pid
                                  select c;
            int i = 1;
            List<Model.Catalogs> catalogses = new List<Model.Catalogs>();
            foreach (var catalogse in StoreSmallClass)
            {
                var clg = catalogse;

                clg.ClassID = catalogse.ClassID;
                clg.ClassName = "[" + i + "]--" + clg.ClassName;

                catalogses.Add(clg);
                i++;
            }
            store3SmallID.DataSource = catalogses;
            store3SmallID.DataBind();
        }
    }

    [DirectMethod]
    public static string GetGrid(Dictionary<string, string> parameters)
    {
        int ctmid = int.Parse(parameters["id"]);
        using (var m = new ACEntities())
        {
            //long LID = long.Parse(id);
            //int uid = int.Parse(Cookies.getCookies("uid"));
            //var q = from c in m.VWCustomers
            //        where c.CTMID == LID && c.isStatus == false && c.LastUserID == uid
            //        orderby c.inTime descending
            //        select c;
            var q = from c in m.VWCustomers
                    where c.CTMID == ctmid && c.isStatus == false && c.LastUserID != null
                    orderby c.inTime descending
                    select c;
            GridPanel grid = new GridPanel
            {
                Height = 200,
                EnableColumnHide = false,
                Store =
                        {
                            new Store
                                {
                                    Model =
                                        {
                                            new Ext.Net.Model
                                                {
                                                    IDProperty = "ID",
                                                    Fields =
                                                        {
                                                            new ModelField("ID"),
                                                            new ModelField("CTMID"),
                                                            new ModelField("BigClassID"),
                                                            new ModelField("SmallClassID"),
                                                            new ModelField("CTMCompany"),
                                                            new ModelField("CTMUsername"),
                                                            new ModelField("CTMPhone"),
                                                            new ModelField("CTMFax"),
                                                            new ModelField("CTMEmail"),
                                                            new ModelField("CTMAddress"),
                                                            new ModelField("LastTime", ModelFieldType.Date),
                                                            new ModelField("LastUserID"),
                                                            new ModelField("LastStatus"),
                                                            new ModelField("LastUserID"),
                                                            new ModelField("LastStatus"),
                                                            new ModelField("LastRemarks"),
                                                            new ModelField("NextContectTime"),
                                                            new ModelField("isStatus"),
                                                            new ModelField("inTime", ModelFieldType.Date),
                                                            new ModelField("Status"),
                                                            new ModelField("BigClass"),
                                                            new ModelField("username"),
                                                            new ModelField("SmallClass") 
                                                        }
                                                }
                                        },
                                    DataSource = q
                                }
                        },
                ColumnModel =
                {
                    Columns =
                                {  
                                    //new Column {Text = "大類", DataIndex = "BigClass"},
                                    //new Column {Text = "小類", DataIndex = "SmallClass"},
                                    new Column {Text = "公司", DataIndex = "CTMCompany" },
                                    new Column {Text = "姓名", DataIndex = "CTMUsername"},
                                    new Column {Text = "电邮", DataIndex = "CTMEmail"},
                                    new Column {Text = "電話", DataIndex = "CTMPhone"},
                                    new Column {Text = "傳真", DataIndex = "CTMFax"},
                                    new Column {Text = "地點", DataIndex = "CTMAddress"},
                                    new DateColumn {Text = "上次日期", DataIndex = "LastTime",Format = "yyyy-MM-dd"},
                                    new Column {Text = "員工", DataIndex = "username"},
                                    new Column {Text = "上次情況", DataIndex = "Status"},
                                    new Column {Text = "內容", DataIndex = "LastRemarks",Flex = 1},
                                    new DateColumn {Text = "提醒日期", DataIndex = "NextContectTime",Format = "yyyy-MM-dd"},
                                    new DateColumn {Text = "时间", DataIndex = "inTime",Format = "yyyy-MM-dd HH:mm"}
                                }
                }


            };

            return ComponentLoader.ToConfig(grid);
        }
    }

    protected void RecorderOperates(object sender, DirectEventArgs e)
    {
        int id = int.Parse(e.ExtraParams["id"].ToString());
        string cmd = e.ExtraParams["cmd"].ToString();
        int uid = int.Parse(Cookies.getCookies("uid"));
        using (var m = new ACEntities())
        {
            var q = (from c in m.Customers
                     where c.CTMID == id && c.isStatus == true
                     select c).FirstOrDefault();
            switch (cmd)
            {
                case "BuYao":
                    var c1 = new global::Model.Customers();
                    c1.CTMID = q.CTMID;
                    c1.BigClassID = q.BigClassID;
                    c1.SmallClassID = q.SmallClassID;
                    c1.CTMCompany = q.CTMCompany;
                    c1.CTMUsername = q.CTMUsername;
                    c1.CTMPhone = q.CTMPhone;
                    c1.CTMFax = q.CTMFax;
                    c1.CTMEmail = q.CTMEmail;
                    c1.CTMAddress = q.CTMAddress;
                    c1.LastTime = DateTime.Now;
                    c1.LastUserID = uid;
                    c1.LastStatus = 2;
                    c1.LastRemarks = "";
                    c1.NextContectTime = null;
                    c1.isStatus = true;
                    c1.inTime = DateTime.Now;
                    m.AddToCustomers(c1);
                    q.isStatus = false;
                    m.SaveChanges();
                    X.AddScript("#{GridPanel1}.store.load();");
                    break;

                case "WeiJie":
                    var c2 = new global::Model.Customers();
                    c2.CTMID = q.CTMID;
                    c2.BigClassID = q.BigClassID;
                    c2.SmallClassID = q.SmallClassID;
                    c2.CTMCompany = q.CTMCompany;
                    c2.CTMUsername = q.CTMUsername;
                    c2.CTMPhone = q.CTMPhone;
                    c2.CTMFax = q.CTMFax;
                    c2.CTMEmail = q.CTMEmail;
                    c2.CTMAddress = q.CTMAddress;
                    c2.LastTime = DateTime.Now;
                    c2.LastUserID = uid;
                    c2.LastStatus = 1;
                    c2.LastRemarks = "";
                    c2.NextContectTime = null;
                    c2.isStatus = true;
                    c2.inTime = DateTime.Now;
                    m.AddToCustomers(c2);
                    q.isStatus = false;
                    m.SaveChanges();
                    X.AddScript("#{GridPanel1}.store.load();");
                    break;
                case "GenJin":
                    CTMID.Clear();
                    BigClassID.Clear();
                    SmallClassID.Clear();
                    CTMCompany.Clear();
                    CTMUsername.Clear();
                    CTMPhone.Clear();
                    CTMFax.Clear();
                    CTMEmail.Clear();
                    CTMAddress.Clear();
                    CTMLastRemarks.Clear();
                    CTMNextContectTime.Value = DateTime.Now;
                    CTMID.Text = q.CTMID.ToString();
                    BigClassID.SetValue(q.BigClassID);
                    CTMLastRemarks.Text = q.LastRemarks;
                    CTMCompany.SetValue(q.CTMCompany.ToString());
                    CTMUsername.SetValue(q.CTMUsername);
                    CTMPhone.SetValue(q.CTMPhone);
                    CTMFax.SetValue(q.CTMFax.ToString());
                    CTMEmail.SetValue(q.CTMEmail);
                    CTMAddress.SetValue(q.CTMAddress);
                    Window1.Show();
                    X.AddScript("#{StoreSC1}.reload();");
                    SmallClassID.SetValue(q.SmallClassID);
                    break;
                case "BianJi":
                    tf3CTMID.Clear();
                    tf3Address.Clear();
                    tf3BigID.Clear();
                    tf3CTMID.Clear();
                    tf3CompanyName.Clear();
                    tf3Email.Clear();
                    tf3Fax.Clear();
                    tf3Phone.Clear();
                    tf3SmallID.Clear();
                    tf3Username.Clear();
                    
                    tf3CTMID.Text = q.CTMID.ToString();
                    tf3CompanyName.Text = q.CTMCompany.ToString();
                    tf3Username.Text = q.CTMUsername.ToString();
                    tf3Phone.Text = q.CTMPhone.ToString();
                    tf3Email.Text = q.CTMEmail.ToString();
                    tf3Fax.Text = q.CTMFax.ToString();
                    tf3BigID.SetValue(q.BigClassID);
                    Window3.Show();
                    X.AddScript("#{store3SmallID}.reload();"); 
                    tf3SmallID.SetValue(q.SmallClassID);
                    
                   
                    break;
                default:
                    break;
            }
        }
    }

    protected void BindGP(object sender, DirectEventArgs e)
    {
        int s = int.Parse(e.ExtraParams["s"]);

        int bid = 0;
        int sid = 0;
        string url = "~/Customers.aspx?s=" + s;
        if (s == 5)
        {
            if (ComboBox1.SelectedItem.Index != -1)
            {
                url = url + "&bid=" + ComboBox1.SelectedItem.Value;
            }
            //X.Msg.Alert("AA",bid.ToString()).Show();
            if (ComboBox2.SelectedItem.Index != -1)
            {
                url = url + "&sid=" + ComboBox2.SelectedItem.Value;
            }
        }

        Response.Redirect(url);
    }

    protected void SaveGenJin(object sender, DirectEventArgs e)
    {
        int ctmid = int.Parse(CTMID.Text);
        int uid = int.Parse(Cookies.getCookies("uid"));
        using (var m = new ACEntities())
        {
            var q = (from c in m.Customers
                     where c.CTMID == ctmid && c.isStatus == true
                     select c).FirstOrDefault();
            var c1 = new global::Model.Customers();
            c1.CTMID = q.CTMID;
            c1.BigClassID = int.Parse(BigClassID.SelectedItem.Value);
            c1.SmallClassID = int.Parse(SmallClassID.SelectedItem.Value);
            c1.CTMCompany = CTMCompany.Text;
            c1.CTMUsername = CTMUsername.Text;
            c1.CTMPhone = CTMPhone.Text;
            c1.CTMFax = CTMFax.Text;
            c1.CTMEmail = CTMEmail.Text;
            c1.CTMAddress = CTMAddress.Text;
            c1.LastTime = DateTime.Now;
            c1.LastUserID = uid;
            c1.LastStatus = int.Parse(CTMLastStatus.SelectedItem.Value);
            c1.LastRemarks = CTMLastRemarks.Text;
            //X.Msg.Alert("AA",CTMNextContectTime.Value.ToString()).Show();
            if (!CTMNextContectTime.Value.ToString().StartsWith("0"))
            {
                c1.NextContectTime = DateTime.Parse(CTMNextContectTime.Value.ToString());
            }

            c1.inTime = DateTime.Now;
            c1.isStatus = true;
            m.AddToCustomers(c1);
            q.isStatus = false;
            m.SaveChanges();
            X.AddScript("#{GridPanel1}.store.load();");
            Window1.Hide();
        }
    }

    protected void BtnBind(int s)
    {
        
    }

    protected void Store1_Refresh(object sender, StoreReadDataEventArgs e)
    {
        int start = int.Parse(e.Parameters["startRemote"]);
        int limit = int.Parse(e.Parameters["limitRemote"]);
        int s = int.Parse(StatusID.SelectedItem.Value);
        int uid = int.Parse(Cookies.getCookies("uid")); 
        int bigClassId = 0;
        int smallID = 0;
        string keywords = TFKey.Text;
        if (ComboBox1.SelectedItem.Index != -1)
        {
            bigClassId = int.Parse(ComboBox1.SelectedItem.Value);
        }
        if (ComboBox2.SelectedItem.Index != -1)
        {
            smallID = int.Parse(ComboBox2.SelectedItem.Value);
        }
        

        using (var m = new ACEntities())
        {
            Store store = this.GridPanel1.GetStore();
            int result = 0; 
            var qqqq = from c in m.VWCustomersForSearch
                     where c.isStatus == true 
                     select c;
            
            if (bigClassId != 0)
            {
                qqqq = qqqq.Where(x => x.BigClassID == bigClassId);
            }
            if (smallID != 0)
            {
                qqqq = qqqq.Where(x => x.SmallClassID == smallID);
            }
            if (s != 0)
            {
                qqqq = qqqq.Where(x => x.LastStatus == s);
            }
            if (keywords.Trim() != "")
            {
                qqqq = qqqq.Where(x => x.forsearch.Contains(keywords));
                qqqq = qqqq.OrderBy(x => x.ID);
                store.DataSource = qqqq.Skip(start).Take(limit);
            }
            else
            {
                if (s == 0)
                {
                    qqqq = qqqq.OrderBy(x => x.ID);
                    store.DataSource = qqqq.Skip(start).Take(limit);
                }
                else
                {
                    var q = from c in qqqq
                            where c.LastStatus == 4 || (c.LastStatus != 4 && c.LastUserID == uid)
                            select c;
                    q = q.OrderBy(x => x.ID);
                    store.DataSource = q.Skip(start).Take(limit); 
                }
                
            }
            
            store.DataBind();
        }


    }

    protected void PageClick(object sender, DirectEventArgs e)
    {
        int page = int.Parse(pageindex.Text);
        int method = int.Parse(e.ExtraParams["s"]);
        page += method;
        if (page <= 0)
        {
            page = 0;
        }

        pageindex.Text = page.ToString();

    }

    protected void OpenDirectInput(object sender, DirectEventArgs e)
    {
        Window2.Show();
    }

    protected void DirectInputsMethod(object sender, DirectEventArgs e)
    {
        //CTMLastRemarks.Text = tbUsers.Text;
        StringBuilder sb = new StringBuilder();
        if (TF1.Text != "")
        {
            string s = "挂墙机";
            s = s.PadRight(10, '-');
            string s2 = TF1.Text;
            string s3 = TextField1.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        if (TF2.Text != "")
        {
            string s = "柜机";
            s = s.PadRight(10, '-');
            string s2 = TF2.Text;
            string s3 = TextField2.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        if (TF3.Text != "")
        {
            string s = "窗口机";
            s = s.PadRight(10, '-');
            string s2 = TF3.Text;
            string s3 = TextField3.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        if (TF4.Text != "")
        {
            string s = "天花/口琴机";
            s = s.PadRight(10, '-');
            string s2 = TF4.Text;
            string s3 = TextField4.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        if (TF5.Text != "")
        {
            string s = "水塔";
            s = s.PadRight(10, '-');
            string s2 = TF5.Text;
            string s3 = TextField5.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        if (TF6.Text != "")
        {
            string s = "中央机";
            s = s.PadRight(10, '-');
            string s2 = TF6.Text;
            string s3 = TextField6.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        if (TF7.Text != "")
        {
            string s = "其他";
            s = s.PadRight(10, '-');
            string s2 = TF7.Text;
            string s3 = TextField7.Text;
            sb.Append(s + "\t\t数量:" + s2 + "\t价钱:" + s3 + "\n");
        }
        CTMLastRemarks.Text = sb.ToString();
        Window2.Hide();
    }

    protected void OpenAddNewCustomer(object sender, DirectEventArgs e)
    {
        tf3CTMID.Clear();
        tf3Address.Clear();
        tf3BigID.Clear();
        tf3CTMID.Clear();
        tf3CompanyName.Clear();
        tf3Email.Clear();
        tf3Fax.Clear();
        tf3Phone.Clear();
        tf3SmallID.Clear();
        tf3Username.Clear();

        Window3.Show();
    }

    protected void AddNewCustomer(object sender, DirectEventArgs e)
    {
        using (var m = new ACEntities())
        {
            int ctmid = 0;
            if (tf3CTMID.Text != "")
            {
                ctmid = int.Parse(tf3CTMID.Text);
            }
            if (ctmid!=0)
            {
                var ctms = (from c in m.Customers
                           where c.CTMID == ctmid
                           select c);
                foreach (var ctm in ctms)
                {
                    ctm.CTMUsername = tf3Username.Text;
                    ctm.BigClassID = int.Parse(tf3BigID.SelectedItem.Value);
                    ctm.SmallClassID = int.Parse(tf3SmallID.SelectedItem.Value);
                    ctm.CTMCompany = tf3CompanyName.Text;
                    ctm.CTMPhone = tf3Phone.Text;
                    ctm.CTMFax = tf3Fax.Text;
                    ctm.CTMEmail = tf3Email.Text;
                    ctm.CTMAddress = tf3Address.Text;  
                }
                m.SaveChanges();
                X.AddScript("#{GridPanel1}.store.load();");
                Window3.Hide();
            }
            else
            {
                var ctm = new Model.Customers();
                ctm.CTMID = int.Parse(GetTimeStamp());
                ctm.CTMUsername = tf3Username.Text;
                ctm.BigClassID = int.Parse(tf3BigID.SelectedItem.Value);
                ctm.SmallClassID = int.Parse(tf3SmallID.SelectedItem.Value);
                ctm.CTMCompany = tf3CompanyName.Text;
                ctm.CTMPhone = tf3Phone.Text;
                ctm.CTMFax = tf3Fax.Text;
                ctm.CTMEmail = tf3Email.Text;
                ctm.CTMAddress = tf3Address.Text;
                ctm.LastUserID = int.Parse(Cookies.getCookies("uid"));
                ctm.LastStatus = 4;
                ctm.isStatus = true;
                ctm.inTime = DateTime.Now;
                m.AddToCustomers(ctm);
                m.SaveChanges();
                X.AddScript("#{GridPanel1}.store.load();");
                Window3.Hide();
            }
            
        }
    }
    /// <summary>
    /// 获取时间戳
    /// </summary>
    /// <returns></returns>
    protected static string GetTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
}